package com.hbnu.controller;

import com.hbnu.pojo.User;
import com.hbnu.service.UserService;
import com.hbnu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/password.action")
public class PasswordServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action=req.getParameter("action");
        User user=(User)req.getSession().getAttribute("session_user");

        if(action!=null&& action.equals("preChange")){
            req.setAttribute("mainRight","/jsp/passwordChange.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req,resp);
        } else if (action!=null&&"ajaxOldPassword".equals(action)) {
            String oldPassword=req.getParameter("oldPassword");
            String password=user.getPassword();

            if(!password.equals(oldPassword)){
                req.setCharacterEncoding("utf-8");
                PrintWriter writer=resp.getWriter();
                writer.println("您输入的原始密码错误，请重新输入！");
            }
        }else if (action!=null&&action.equals("change")){
            String newPassword=req.getParameter("newPassword");
            user.setPassword(newPassword);
            userService.updatePassword(user);
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }
}
